package com.hiss.basic.starter.websocket.handler;

import cn.hutool.core.util.StrUtil;
import com.hiss.basic.starter.core.exception.BusinessException;
import com.hiss.basic.starter.websocket.model.PrincipalModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

@Slf4j
public class PrincipalHandshakeHandler extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler handler, Map<String, Object> attributes) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
            HttpServletRequest servletRequest = servletServerHttpRequest.getServletRequest();
            String userId = servletRequest.getParameter("userId");
            String channel = servletRequest.getParameter("channel");
            log.info("WebSocket 握手确认: userId={}, channel={}", userId, channel);
            if (StrUtil.isAllNotBlank(userId, channel)) {
                return () -> new PrincipalModel(userId, channel).toString();
            }
        }
        throw new BusinessException("WebSocket user id or channel is missing.");
    }
}
